<?php declare(strict_types=1);

namespace think\msg\platform\feishu\convertor;

use think\msg\msg\RichTextMsg;
use think\msg\msg\TextMsg;
use think\msg\platform\feishu\dto\RichTextMsgDto;
use think\msg\platform\feishu\dto\TextMsgDto;

final class MsgConvertor
{
    /**
     * 通用纯文本消息转换成飞书的文本消息
     * @param TextMsg $msg
     * @return TextMsgDto
     */
    public static function toTextMsgDto(TextMsg $msg): TextMsgDto
    {
        $textMsgDto = new TextMsgDto();
        $textMsgDto->setText($msg->getContent());
        return $textMsgDto;
    }

    public static function toRichTextMsgDto(RichTextMsg $msg): RichTextMsgDto
    {
        $richTextMsgDto = new RichTextMsgDto();
        $richTextMsgDto->setTitle($msg->getTitle());
        $contentList = $msg->getContent();
        $data = [];
        foreach ($contentList as $key => $content) {
            foreach ($content as $item) {
                if ('text' === $item['tag'] ?? '') {
                    $data[$key][] = [
                        'tag' => 'text',
                        'text' => $item['text'],
                    ];
                } elseif ('at' === $item['tag'] ?? '') {
                    $data[$key][] = [
                        'type' => 'at',
                        'user_id' => $item['user_id'],
                    ];
                } elseif ('a' === $item['tag'] ?? '') {
                    $data[$key][] = [
                        'tag' => 'a',
                        'href' => $item['url'],
                        'text' => $item['text'],
                    ];
                } elseif ('img' === $item['tag'] ?? '') {
                    $data[$key][] = [
                        'tag' => 'img',
                        'img_key' => $item['img_key'],
                        'alt' => $item['alt'],
                    ];
                }
            }
        }
        $richTextMsgDto->setContent($data);
        return $richTextMsgDto;
    }
}
